package my.study.java.util.HashMap;

import java.util.ArrayList;
import java.util.HashMap;

public class PerformanceAnalysis {

	/**
	 * 
	 * HashMap与对象存储性能比较，结论HashMap占用内存较大，而且处理时间较长，时间和内存都大概为3-5倍
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		PerformanceAnalysis1();
		Thread.sleep(10000);
		PerformanceAnalysis2();
	}

	public static void PerformanceAnalysis1() {
		System.out.println("PerformanceAnalysis.PerformanceAnalysis1()");
		long start  = System.currentTimeMillis();
		ArrayList<User> users= new ArrayList<User>();
		for (int i = 0; i < 100000; i++) {
			User user = new User();
			user.s1 = "string1" + i;
			user.s2 = "string2" + i;
			user.s3 = "string3" + i;
			users.add(user);
		}
		Runtime r = Runtime.getRuntime();  
		pl("free memory: " + r.freeMemory());
		pl("max memory: " + r.maxMemory());
		pl("total memory: " + r.totalMemory());
		users = null;
		System.out.println("It takes " + (System.currentTimeMillis() - start)  + " ms");
		System.gc();
	}
	
	public static void PerformanceAnalysis2() {
		System.out.println("PerformanceAnalysis.PerformanceAnalysis2()");
		long start  = System.currentTimeMillis();
		ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
		for (int i = 0; i < 100000; i++) {
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("string1" + i, "value1" + i);
			map.put("string2" + i, "value2" + i);
			map.put("string3" + i, "value3" + i);
			list.add(map);
		}
		Runtime r = Runtime.getRuntime();  
		pl("free memory: " + r.freeMemory());
		pl("max memory: " + r.maxMemory());
		pl("total memory: " + r.totalMemory());		
		System.out.println("It takes " + (System.currentTimeMillis() - start)  + " ms");
		System.gc();
	}
	public static void pl(Object o) {
		System.out.println(o);
	}
}
class User {
	String s1;
	String s2;
	String s3;
}
